<!-- 短租其它 确认费用 -->
<template>
  <a-modal
    v-model:visible="showModal"
    @close="onClose"
    @before-ok="submitFn"
    title="修改信息"
    class="modal-dialog-wrapper"
    unmount-on-close
    :mask-closable="false"
    width="65vw"
  >
    <div class="fee-page">
      <div class="fee-list">
        <div v-for="(item, index) in feeList" :key="index" style="margin: 0 20px">
          <feeitemShortOrder :fee="item" v-if="bizType == 1" />
          <feeitemLongOrder :fee="item" v-if="bizType == 4" />
          <template v-if="bizType == 2">
            <feeitemViolation v-if="item.feeCategory && item.feeCategory == 4" :fee="item" />
            <feeitemAssets
              v-if="item.feeCategory == 1 || item.feeCategory == 2 || item.feeCategory == 3"
              :fee="item"
              :supplierType="item.feeCategory"
            />
            <!-- <feeitemTransfer v-if="item.feeCategory == 6" :record="item" /> -->
            <feeitemPurchase v-if="item.feeCategory == 0 || item.feeCategory == 5 || item.feeCategory == 6" :fee="item" />
          </template>
        </div>
        <div class="all-cost">
          <span>合计</span>
          <div class="cost-num">
            <div>{{ feeCostAmount.orderAmount > 0 ? '应收' : '应付' }}：{{ unitVal(Math.abs(feeCostAmount.orderAmount), '元') }}</div>
            <div style="margin-top: 16px"> {{ feeCostAmount.orderAmount > 0 ? '待收' : '待付' }}：0元 </div>
          </div>
        </div>
      </div>

      <a-divider />

      <page-form :model="form" layout="vertical" ref="formRef" style="margin-top: 40px">
        <page-form-row>
          <page-form-item
            field="actualAmount"
            :label="costName + '金额'"
            :rules="{ required: true, message: '请输入' + costName + '金额' }"
          >
            <i-input-number v-model="form.actualAmount" unit="元" :precision="2" disabled />
          </page-form-item>
          <page-form-item
            field="paymentWay"
            :label="costName + '方式'"
            :rules="{ required: true, message: '请选择' + costName + '方式' }"
            labelTooltipContent="收/付款方式支持在系统管理菜单下的收支账号管理页面进行配置。"
          >
            <a-select
              placeholder="请选择"
              v-model="form.paymentWay"
              @change="typeChange"
              :disabled="disabledCostType || form.paymentWay == -1 || (currentPaymentWay == 4 && costName == '付款')"
              :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
              allow-clear
              popup-container="#app"
            >
              <a-option v-for="item in paywayEnum" :key="item.way" :value="item.way" :label="item.wayStr" />
            </a-select>
          </page-form-item>
          <page-form-item v-if="form.paymentWay == -1" field="payAccountId" label="结算主体" :rules="{ required: true, message: '请选择' }">
            <a-select :placeholder="'请选择'" v-model="form.payAccountId" disabled>
              <a-option v-for="item in accountList" :key="item.id" :value="item.id" :label="item.bank" />
            </a-select>
          </page-form-item>
          <page-form-item
            v-else
            field="payAccountId"
            :label="costName + '账号'"
            labelTooltipContent="收/付款账号支持在系统管理菜单下的收支账号管理页面进行配置。"
          >
            <a-select
              :placeholder="!form.paymentWay ? '请先选择' + costName + '方式' : '请选择'"
              v-model="form.payAccountId"
              :disabled="!form.paymentWay  || (currentPaymentWay == 4 && costName == '付款')"
              :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
              allow-clear
              popup-container="#app"
            >
              <a-option
                v-for="item in accountList"
                :key="item.id"
                :value="item.id"
                :label="item.account + (item.bank ? '_' + item.bank : '')"
              />
            </a-select>
          </page-form-item>
          <page-form-item
            v-if="form.paymentWay && form.paymentWay != -1"
            field="paymentTime"
            :label="costName + '时间'"
            :rules="[{ required: true, message: '请选择' + costName + '时间', trigger: 'change' }]"
            :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
            allow-clear
            popup-container="#app"
          >
            <i-date-picker class="w-full" v-model="form.paymentTime" show-time disabled />
          </page-form-item>
          <!-- 
            短租订单、长租订单、违章订单：输入框，默认展示确认费用时填写的信息
            保养单、维修单、年检单：下拉单选，下拉为保养+维修+年检供应商信息，默认展示确认确认费用时填写的信息
            车辆购置费：下拉单选，下拉为商户下所有的汽车销售名称，默认展示确认费用时填写的信息
            借调单-跨门店调车：下拉单选，下拉为操作人权限下所有的门店，默认展示确认费用时填写的信息
            借调单-借入/借出：下拉单选，下拉为商户下所有的同行名称，默认展示确认费用时填写的信息
          -->

          <page-form-item
            field="customerName"
            label="客户名称"
            :rules="{ required: true, message: '请输入客户名称' }"
            v-if="costSource == 'out'"
          >
            <i-input placeholder="请输入" v-model="form.customerName" :max-length="20" />
          </page-form-item>

          <page-form-item
            field="customerId"
            label="客户名称"
            :rules="{ required: true, message: '请选择客户名称' }"
            v-if="costSource == 1 || costSource == 2 || costSource == 3"
          >
            <a-select
              placeholder="请选择"
              v-model="form.customerId"
              @change="changeCustomerIdType2"
              :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
              allow-clear
              popup-container="#app"
            >
              <a-option v-for="(item, index) in supplierLists" :key="index" :value="item.id"> {{ item.supplierName }}</a-option>
            </a-select>
          </page-form-item>

          <page-form-item
            field="customerId"
            label="客户名称"
            :rules="{ required: true, message: '请选择客户名称' }"
            v-if="costSource == 0 || costSource == 5"
          >
            <a-select
              placeholder="请选择"
              v-model="form.customerId"
              @change="changeCustomerIdType3"
              :trigger-props="{ updateAtScroll: true, scrollToClose: true }"
              allow-clear
              popup-container="#app"
            >
              <a-option v-for="(item, index) in supplierLists" :key="index" :value="item.id"> {{ item.supplierName }}</a-option>
            </a-select>
          </page-form-item>

          <page-form-item
            field="customerId"
            label="客户名称"
            :rules="{ required: true, message: '请选择客户名称' }"
            v-if="costSource == 6 && customerType == 0"
          >
            <remote-select
              v-model="form.customerId"
              placeholder="请选择客户名称"
              type="sameIndustry_list"
              @change="changeCustomerBySameIndustry"
            />
          </page-form-item>

          <page-form-item
            field="customerId"
            label="客户名称"
            :rules="{ required: true, message: '请选择客户名称' }"
            v-if="costSource == 6 && customerType == 2"
          >
            <remote-select
              v-model="form.customerId"
              placeholder="请选择客户名称"
              :params="{ siteType: 40, siteStatusList: [10] }"
              type="site_listBystaff"
              @change="changeCustomerBySite"
            />
          </page-form-item>

          <page-form-item field="customerAccount" :label="costName == '收款' ? '客户付款账号' : '客户收款账号'">
            <i-input placeholder="请输入" v-model="form.customerAccount" :max-length="20" />
          </page-form-item>
          <page-form-item field="remark" label="费用备注" size="2/3">
            <i-input placeholder="请输入" v-model="form.remark" :max-length="200" />
          </page-form-item>
        </page-form-row>
      </page-form>
    </div>
    <template #footer>
      <a-space>
        <a-button @click="onClose">关闭</a-button>
        <a-button type="primary" @click="submitFn">确认</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup name="ConfirmFees" lang="ts">
  import feeitemShortOrder from '../components/comfirm-fee-item-short-order.vue'
  import feeitemLongOrder from '../components/comfirm-fee-item-long-order.vue'
  import feeitemViolation from '../components/comfirm-fee-item-violation.vue'
  import feeitemAssets from '../components/comfirm-fee-item-assets.vue'
  import feeitemTransfer from '../components/comfirm-fee-item-transfer.vue'
  import feeitemPurchase from '@/views/assets/car/car-manage/components/comfirm-fee-item.vue'

  import { Message } from '@arco-design/web-vue'
  import { unitVal } from '@/utils'
  import { getAccountByPageData, getAccountByWayAndType } from '@/api/order/czsOrder'
  import { getOrderRecordDetail, updateRecord } from '@/api/finance/turnover'
  import { getSupplierList } from '@/api/asset/maintenance'
  import { ref } from 'vue'

  // const costType = ref(null) // type  0-收款，1-付款，3-收款&付款  (合计 正-收款  负-付款)
  const paywayEnum = ref<any>([]) //收付款方式
  const accountList = ref<any>([]) //收付款账号列表
  const costType = ref<any>() // 收支类型 10 收款 20 付款
  const costName = ref<any>('')
  const feeList = ref<any>([]) // 收付款列表
  const feeCostAmount = ref<any>({}) //收付款类型及金额
  const bizType = ref<any>()
  const formRef = ref<any>()
  const disabledCostType = ref(false)
  const form = ref<any>({
    idList: [], //结算单ids
    orderId: '',
  })
  // 费用来源
  const costSource = ref()
  const supplierType = ref()
  const customerType = ref() // 0：同行、1：供应商、2：门店
  const supplierTypes = ref<any>([]) // 运维
  const emit = defineEmits(['ok'])
  const currentPaymentWay = ref('') // 收支方式
  // 打开弹窗
  const showModal = ref(false)
  const show = (record: any) => {
    console.log('record', record)

    // 重置
    resetForm()
    showModal.value = true
    currentPaymentWay.value = record.paymentWay
    if (record.id) {
      getFeeDetailApi(record.id)
    }
  }

  const onClose = () => {
    feeCostAmount.value = {}
    supplierTypes.value = []
    feeList.value = []
    showModal.value = false
  }

  const resetForm = () => {
    disabledCostType.value = false
    paywayEnum.value = []
    accountList.value = []
    form.value = {}
  }

  // 去确认
  const getFeeDetailApi = (id: any) => {
    getOrderRecordDetail({ id: id }).then((res: any) => {
      feeCostAmount.value = res.result
      feeList.value = res.result.orderFeeList
      bizType.value = res.result.bizType
      form.value.id = id
      form.value.actualAmount = Math.abs(res.result.orderAmount) //固定金额，不可修改
      costType.value = res.result.recordType
      form.value.recordType = res.result.recordType
      form.value.paymentTime = res.result.paymentTime
      form.value.customerId = res.result.customerId
      form.value.customerName = res.result.customerName
      form.value.customerType = res.result.customerType
      customerType.value = res.result.customerType
      form.value.remark = res.result.remark
      form.value.customerAccount = res.result.customerAccount
      form.value.payAccountId = res.result.payAccountId
      if (res.result.bizType == 1 || res.result.bizType == 4) {
        // 长租、短租
        costSource.value = 'out'
      } else {
        // 0: 车辆购置费
        // 1: 保养
        // 2: 维修
        // 3: 年检
        // 4: 违章
        // 5: 其他费用
        // 6: 借调
        if (feeList.value.length) {
          if (feeList.value[0].feeCategory == 4) {
            costSource.value = 'out'
          } else {
            costSource.value = feeList.value[0].feeCategory
            if (feeList.value[0].feeCategory == 0) {
              supplierType.value = 3
            }
            if (feeList.value[0].feeCategory == 1) {
              supplierType.value = 1
            }
            if (feeList.value[0].feeCategory == 2) {
              supplierType.value = 0
            }
            if (feeList.value[0].feeCategory == 3) {
              supplierType.value = 6
            }
            if (feeList.value[0].feeCategory == 6) {
              supplierType.value = 3
            }
            if (feeList.value[0].feeCategory == 5) {
              supplierType.value = 3
            }
          }
        }

        if (feeList.value.length && feeList.value.length > 1) {
          supplierTypes.value = []
          /**
           * 多条数据时，分运维对账、借调对账、车辆购置费对账；
           * 其中：
           *    运维对账时，需要把所对应的供应商组合起来 feeCategory 为 1、2、3（客户名称选项）
           *    借调对账：无特殊情况 feeCategory 为 6
           *    车辆购置费对账：特殊情况包含其他费用，feeCategory 为 0 和 5
           */

          // 判断多条数据是否为同一种
          //【其中 非运维的对账不需要获取供应商组合】
          let isAssetsFlag = feeList.value.some((ele: any) => {
            return ele.feeCategory == feeList.value[0].feeCategory
          })
          // 判断费用类型是否为车辆购置费
          let isCarPurchaseCost = feeList.value.some((ele: any) => {
            return ele.feeCategory == 0 || ele.feeCategory == 5
          })
          // 是多条运维对账且不为车辆购置费的请求供应商
          if (isAssetsFlag && !isCarPurchaseCost) {
            supplierTypes.value = [0, 1, 6]
          }
          if (supplierTypes.value.length) {
            getSupplierListByMoreType()
          }
        }
      }

      if ((costSource.value || costSource.value == 0) && costSource.value != 'out' && !supplierTypes.value.length) {
        getSupplierListApi()
      }
      if (costType.value == 10) {
        costName.value = '收款'
      } else {
        costName.value = '付款'
      }
      // 押金抵扣为固定收付款方式
      if (feeCostAmount.value.payType != null) {
        disabledCostType.value = true
        form.value.paymentWay = feeCostAmount.value.payType.toString()
      } else {
        form.value.paymentWay = JSON.stringify(res.result.paymentWay)
      }

      getType(res.result)
    })
  }

  // 收付款类型
  const getType = (details: any) => {
    getAccountByPageData({ type: costType.value == 10 ? 0 : 1, oldWay: details.paymentWay }).then((res: any) => {
      let data = res.result
      paywayEnum.value = data.filter((i: any) => i.way != '1' && i.way != '2' && i.way != '3' && i.way != '5')

      if (!disabledCostType.value) {
        paywayEnum.value = paywayEnum.value.filter((i: any) => i.way != '4')
      }

      if (form.value.paymentWay != -1) {
        paywayEnum.value = paywayEnum.value.filter((el: any) => el.way != -1)
      }

      if (form.value.paymentWay) {
        typeChange(form.value.paymentWay, 'first')
      }
    })
  }

  // 账号
  const typeChange = (e: any, times: any) => {
    if (!times) {
      form.value.payAccountId = undefined
    }
    paywayEnum.value.forEach((el: any) => {
      if (el.way == e) {
        getAccountByWayAndType({ way: Number(el.way), type: Number(costType.value == 10 ? 0 : 1) }).then((res: any) => {
          accountList.value = res.result
        })
      }
    })
  }

  const supplierLists = ref<any>([])
  const getSupplierListApi = () => {
    getSupplierList({ supplierType: supplierType.value, status: 1 }).then((res: any) => {
      supplierLists.value = res.result
    })
  }

  const getSupplierListByMoreType = () => {
    getSupplierList({ supplierTypes: supplierTypes.value, status: 1 }).then((res: any) => {
      supplierLists.value = res.result
    })
  }

  const changeCustomerIdType2 = (e: any) => {
    if (supplierLists.value && supplierLists.value.length) {
      supplierLists.value.forEach((item: any) => {
        if (item.id == e) {
          form.value.customerName = item.supplierName
        }
      })
    }
  }

  const changeCustomerIdType3 = (e: any) => {
    if (supplierLists.value && supplierLists.value.length) {
      supplierLists.value.forEach((item: any) => {
        if (item.id == e) {
          form.value.customerName = item.supplierName
        }
      })
    }
  }

  // 选择客户名称（门店）
  const changeCustomerBySite = (_: any, option = {}) => {
    form.value.customerName = option.siteName
  }
  // 选择客户名称（同行）
  const changeCustomerBySameIndustry = (_: any, option = {}) => {
    form.value.customerName = option.industryName
  }

  defineExpose({
    show,
  })

  const submitFn = () => {
    formRef.value.validate((error: any) => {
      if (!error) {
        const param = {
          ...form.value,
        }
        updateRecord(param)
          .then((res: any) => {
            Message.success(res.message)
            showModal.value = false
            emit('ok')
          })
          .finally((error: any) => {
            console.log(error)
            // Message.warning(error.message)
          })
      }
    })
  }
</script>

<style lang="less" scoped>
  .fee-list {
    padding-top: 20px;
    margin-bottom: 80px;
    border: 1px solid #f2f3f5;
  }
  .all-cost {
    font-weight: 600;
    padding: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    background: #f2f3f5;
    height: 100px;
    .cost-num {
      color: #1890ff;
      display: flex;
      flex-direction: column;
      align-items: flex-end;
    }
  }
  // 弹窗添加的样式
  .fee-page {
    position: relative;
    width: 100%;
    max-height: 70vh;

    :deep(.arco-row) {
      margin-left: 0 !important;
      margin-right: 0 !important;
    }
    :deep(.arco-modal-body) {
      padding: 10px 80px !important;
    }
    :deep(.arco-col) {
      padding: 0 10px !important;
    }
  }
</style>
